package com.tangbuzhi.iteraror;

import java.util.ArrayList;
import java.util.List;

/**
 * 迭代器模式
 */
public class IteratorClass {
    public interface IIterator<T> {
        boolean hasNext();

        T next();
    }

    public static class ConcreteIterator<T> implements IIterator<T> {
        private List<T> list = new ArrayList<>();
        private int cursor = 0;

        public ConcreteIterator(List<T> list) {
            this.list = list;
        }

        @Override
        public boolean hasNext() {
            return cursor != list.size();
        }

        @Override
        public T next() {
            T obj = null;
            if (hasNext()) {
                obj = list.get(cursor++);
            }
            return obj;
        }
    }

    public interface Aggregate<T> {
        void add(T obj);

        void remove(T obj);

        IIterator<T> iterator();
    }

    public static class ConcreteAggegate<T> implements Aggregate<T> {
        private List<T> list = new ArrayList<>();

        @Override
        public void add(T obj) {
            list.add(obj);
        }

        @Override
        public void remove(T obj) {
            list.remove(obj);
        }

        @Override
        public IIterator<T> iterator() {
            return new ConcreteIterator(list);
        }
    }

    public static void main(String[] args) {
        Aggregate<String> aggregate = new ConcreteAggegate();
        aggregate.add("android");
        aggregate.add("studio");
        aggregate.add("eclipse");
        aggregate.add("intellij idea");
        IIterator<String> iterator = aggregate.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
